const { UserService } = require("../service/user_service")
// const { parseUrl } = require("../../utils/parseUrlUtils")
const { BaseResult } = require("../../domain/base_result")
const { LOGIN_FAIL, TB_USER_IS_EXIST } = require("../../domain/constance")

const userController = (_ => {

    const userService = new UserService()

    // 获取post请求中的数据
    const getHandlePostDataObj = async req => {
        let body = ""
        let obj = {}
        return new Promise(resolve => {
            req.on('data', function (chunk) {
                body += chunk;
            });
            req.on('end', function () {
                let searchParams = new URLSearchParams(body)
                searchParams.forEach((v, k) => {
                    obj[k] = v;
                })
                resolve(obj)
            });
        })
    }


    // 用户登录 post
    const login = async (req, response) => {

        const obj = await getHandlePostDataObj(req)

        if (!obj) return

        const result = await userService.login(obj.name, obj.password);
        (result && result.length > 0)
            ? response.end(BaseResult.ok(result[0]))
            : response.end(BaseResult.notOk(LOGIN_FAIL))

    }

    // 处理url
    // const handleUrl = (url, response) => {
    //     return new Promise(resolve => {
    //         let obj = parseUrl(url)
    //         // 处理url
    //         if (Object.values(obj).every(item => item === '')) {
    //             response.end(BaseResult.notOk(INVALIE_PARAM))
    //             resolve(null)
    //         }
    //         resolve(obj)
    //     })
    // }

    // 用户注册 post
    const register = async (req, response) => {

        const obj = await getHandlePostDataObj(req)

        if (!obj) return

        const result = await userService.register(obj);

        response.end(BaseResult.ok(result));

    }

    // 查询全部用户信息 get
    const list = async (_, response) => {
        response.end(BaseResult.ok(await userService.getTbUsers()))
    }

    // 保存用户信息 post
    const save = async (req, response) => {

        const obj = await getHandlePostDataObj(req)

        if (!obj) return

        const result = await userService.save(obj)

        response.end(BaseResult.ok(result))

    }

    // 删除用户信息 post
    const remove = async (req, response) => {

        const obj = await getHandlePostDataObj(req)

        if (!obj) return

        const result = await userService.delete(+obj.id)

        response.end(BaseResult.ok(result))

    }

    return {
        login,
        register,
        list,
        save,
        remove
    }

})()

module.exports = {
    userController
}

